package com.yaorange.servlet;

import com.yaorange.dao.CustomerDao;
import com.yaorange.pojo.Customer;
import com.yaorange.util.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
@WebServlet("/queryAll")
public class QueryAll extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        CustomerDao customerDao = sqlSession.getMapper(CustomerDao.class);

        List<Customer> customers = customerDao.queryAll();
        sqlSession.close();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        //将获取到的数据库信息显示到页面
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write("<table>");
        writer.write("<tr><td>客户编号</td><td>客户名称</td><td>客户性别</td><td>客户生日</td><td>注册时间</td>&nbsp&nbsp&nbsp<td>删除</td></tr>");
        for(Customer customer:customers){
            writer.write("<tr>");
            writer.write(
                    "<td>"+customer.getId()+"</td><td>"+customer.getName()+"</td><td>"+customer.getGender()
                    +"</td><td>"+df.format(customer.getBirthday())+"</td><td>"+df.format(customer.getRegistTime())+
                    "</td>&nbsp&nbsp&nbsp<td>"+"<a href='"+req.getContextPath()+"/delById?id="+customer.getId()+"'>删除</a></td>");
            writer.write("</tr>");
        }

        writer.write("</table>");
        writer.close();
    }
}
